package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.Order;
import cn.edu.tju.elm.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@Tag(name = "管理订单", description = "对订单进行增删改查")
public class OrderController {
    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @PostMapping("")
    @Operation(summary = "创建订单", description = "创建新的订单")
    public HttpResult<Order> createOrder(@RequestBody Order order) {
        try {
            Order savedOrder = orderService.createOrder(order);
            return HttpResult.success(savedOrder);
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "创建订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取订单详情", description = "根据ID获取订单详细信息")
    public HttpResult<Order> getOrder(@PathVariable("id") Long id) {
        Optional<Order> order = orderService.getOrderById(id);
        if(order.isPresent()) {
            return HttpResult.success(order.get());
        } else {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
        }
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户订单", description = "获取指定用户的所有订单")
    public HttpResult<List<Order>> getUserOrders(@PathVariable("userId") Long userId) {
        List<Order> orders = orderService.getOrdersByUserId(userId);
        return HttpResult.success(orders);
    }
    
    @PutMapping("/{id}/state")
    @Operation(summary = "更新订单状态", description = "更新指定订单的状态")
    public HttpResult<Order> updateOrderState(@PathVariable("id") Long id, @RequestParam("state") Integer state) {
        Order updatedOrder = orderService.updateOrderState(id, state);
        if(updatedOrder != null) {
            return HttpResult.success(updatedOrder);
        } else {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
        }
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除订单", description = "删除指定ID的订单")
    public HttpResult<Void> deleteOrder(@PathVariable("id") Long id) {
        boolean deleted = orderService.deleteOrder(id);
        if(deleted) {
            return HttpResult.success();
        } else {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
        }
    }
}
